package com.hsl.test.utils;

import com.hsl.test.aop.TService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @author hsl
 * @Data 2021/12/14
 * @Desc
 */
@TService
public class ConnectionUtil {
    //存储当前线程的链接
    private final ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public Connection getCurrentConn() throws SQLException {
        //先从当前线程中获取是否已存在的连接
        Connection connection = threadLocal.get();
        // 如果当前线程没有已存在的数据库连接，就从连接池获取连接,保存到当前线程中
        if (Objects.isNull(connection)) {
            //从连接池获取连接
            connection = DruidUtil.getInstance().getConnection();
            // 保存到当前线程中
            threadLocal.set(connection);
        }
        return connection;
    }
}
